package com.zzyl.serve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.serve.domain.NursingPlan;
import com.zzyl.serve.domain.NursingProjectPlan;
import com.zzyl.serve.dto.NursingPlanDto;
import com.zzyl.serve.mapper.NursingPlanMapper;
import com.zzyl.serve.service.INursingPlanService;
import com.zzyl.serve.service.INursingProjectPlanService;
import com.zzyl.serve.vo.NursingPlanVo;
import com.zzyl.serve.vo.NursingProjectPlanVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 护理计划Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-04
 */
@Service
public class NursingPlanServiceImpl extends ServiceImpl<NursingPlanMapper, NursingPlan> implements INursingPlanService {
    @Autowired
    private NursingPlanMapper nursingPlanMapper;
    @Autowired
    private INursingProjectPlanService nursingProjectPlanService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询护理计划列表
     *
     * @param nursingPlan 护理计划
     * @return 护理计划
     */
    @Override
    public List<NursingPlan> selectNursingPlanList(NursingPlan nursingPlan) {
        return nursingPlanMapper.selectNursingPlanList(nursingPlan);
    }

    /**
     * 新增护理计划
     *
     * @param dto 护理计划
     * @return 结果
     */
    @Transactional
    @Override
    public int insertNursingPlan(NursingPlanDto dto) {
        //1.向主表中插入数据
        NursingPlan nursingPlan = BeanUtil.toBean(dto, NursingPlan.class);
        save(nursingPlan); //save保存完数据后，自动主键返回给nursingPlan对象
        //2.向子表中批量插入数据
        List<NursingProjectPlan> projectPlans = dto.getProjectPlans();
        if (ObjectUtil.isEmpty(projectPlans)) {
            return 1;
        }
        projectPlans.forEach(projectPlan -> projectPlan.setPlanId(nursingPlan.getId()));
        boolean result = nursingProjectPlanService.saveBatch(projectPlans);
        // new 删除缓存
        if (result) {
            redisTemplate.delete(CacheConstants.CACHE_KEY_NURSING_PLAN);
        }
        //3.返回结果
        return result ? 1 : 0;
    }

    /**
     * 查询护理计划详细信息
     *
     * @param id 护理计划主键
     * @return 护理计划
     */
    @Override
    public NursingPlanVo selectNursingPlanById(Long id) {
        // 1. 查询主表数据
        NursingPlan nursingPlan = getById(id);
        if (ObjectUtil.isEmpty(nursingPlan)) {
            return null;
        }
        // 2. 获取子表护理项目计划数据
        List<NursingProjectPlan> nursingProjectPlans = nursingProjectPlanService.lambdaQuery().eq(NursingProjectPlan::getPlanId, id)
                .list();
        if (ObjectUtil.isEmpty(nursingProjectPlans)) {
            return null;
        }
        List<NursingProjectPlanVo> projectPlanVoList = nursingProjectPlans.stream().map(nursingProjectPlan -> {
            NursingProjectPlanVo vo = BeanUtil.toBean(nursingProjectPlan, NursingProjectPlanVo.class);
            vo.setProjectId(nursingProjectPlan.getProjectId().toString());
            vo.setExecuteCycle(nursingProjectPlan.getExecuteCycle().toString());
//            vo.setExecuteFrequency(Long.valueOf(nursingProjectPlan.getExecuteFrequency()));
            vo.setExecuteFrequency(nursingProjectPlan.getExecuteFrequency().longValue());
            return vo;
        }).collect(Collectors.toList());
        // 3. 封装数据并返回
        NursingPlanVo nursingPlanVo = BeanUtil.toBean(nursingPlan, NursingPlanVo.class);
        nursingPlanVo.setProjectPlans(projectPlanVoList);
        return nursingPlanVo;
    }

    /**
     * 修改护理计划
     *
     * @param dto 护理计划
     * @return 结果
     */
    @Transactional
    @Override
    public int updateNursingPlan(NursingPlanDto dto) {
        // 参数校验
        if (dto == null || dto.getId() == null) {
            return 0;
        }
        //1.修改主表数据
        NursingPlan nursingPlan = BeanUtil.toBean(dto, NursingPlan.class);
        boolean result = updateById(nursingPlan);
        //2.删除子表数据,并再次批量插入前端传递的子表数据
        nursingProjectPlanService.lambdaUpdate().eq(NursingProjectPlan::getPlanId, nursingPlan.getId()).remove();
        List<NursingProjectPlan> projectPlans = dto.getProjectPlans();
        if (ObjectUtil.isNotEmpty(projectPlans)) {
            projectPlans.forEach(projectPlan -> projectPlan.setPlanId(dto.getId()));
            nursingProjectPlanService.saveBatch(projectPlans);
        }
        // new 删除缓存
        if (result) {
            redisTemplate.delete(CacheConstants.CACHE_KEY_NURSING_PLAN);
        }
        //3.返回结果
        return result ? 1 : 0;
    }

    /**
     * 批量删除护理计划
     *
     * @param ids 需要删除的护理计划主键
     * @return 结果
     */
    @Override
    public int deleteNursingPlanByIds(Long[] ids) {
        boolean result = removeByIds(Arrays.asList(ids));
        nursingProjectPlanService.lambdaUpdate().in(NursingProjectPlan::getPlanId, ids).remove();
        // new 删除缓存
        if (result) {
            redisTemplate.delete(CacheConstants.CACHE_KEY_NURSING_PLAN);
        }
        return result ? 1 : 0;
    }

    /**
     * 删除护理计划信息
     *
     * @param id 护理计划主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteNursingPlanById(Long id) {
        boolean result = removeById(id);
        nursingProjectPlanService.lambdaUpdate().eq(NursingProjectPlan::getPlanId, id).remove();
        // new 删除缓存
        if (result) {
            redisTemplate.delete(CacheConstants.CACHE_KEY_NURSING_PLAN);
        }
        return result ? 1 : 0;
    }

    /**
     * 查询所有护理计划
     *
     * @return 护理计划集合
     */
    @Override
    public List<NursingPlan> listAll() {
        // 1.先从缓存中获取
        List<NursingPlan> nursingPlans = (List<NursingPlan>) redisTemplate.opsForValue().get(CacheConstants.CACHE_KEY_NURSING_PLAN);
        // 2.缓存中存在则返回
        if (nursingPlans != null){
            return nursingPlans;
        }
        // 3.缓存中不存在则从数据库中查询,并保存到缓存中
        LambdaQueryWrapper<NursingPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NursingPlan::getStatus, 1);
        List<NursingPlan> nursingPlansDB = list(queryWrapper);
        redisTemplate.opsForValue().set(CacheConstants.CACHE_KEY_NURSING_PLAN, nursingPlansDB);
        return nursingPlansDB;
    }
}
